//
//  FFOpenRedPacketVC.m
//  LiMaoRedPackets
//
//  Created by JayLuo on 2020/8/26.
//
//

#import <UIKit/UIKit.h>
#import "FFOpenRedPacketVC.h"
#import <WuKongBase/WuKongBase.h>
#import <QuartzCore/QuartzCore.h>
#import "Masonry.h"

//*******************************
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ViewScaleIphone5Value ([UIScreen mainScreen].bounds.size.width/320.0f)


#if __IPHONE_OS_VERSION_MAX_ALLOWED < 100000
// CAAnimationDelegate is not available before iOS 10 SDK
@interface FFOpenRedPacketVC ()<UIGestureRecognizerDelegate>
#else
@interface FFOpenRedPacketVC () <CAAnimationDelegate,UIGestureRecognizerDelegate>
#endif

@property (nonatomic,strong) UIWindow       *alertWindow;
@property (nonatomic,strong) UIImageView    *backgroundImageView;
@property (nonatomic,strong) FFRewardConfig *data;
@property (nonatomic,strong) UIImageView    *avatarImageView;
@property (nonatomic,strong) UILabel        *userNameLabel;
@property (nonatomic,strong) UILabel        *tipsLabel;
@property (nonatomic,strong) UILabel        *messageLabel;
@property (nonatomic,strong) UIButton       *openButton;
@property (nonatomic,strong) UIButton       *closeButton;
@property (nonatomic,strong) UIButton       *checkDetailButton;

@property (nonatomic,copy) LIMCancelBlock    cancelBlock;
@property (nonatomic,copy) LIMFinishBlock    finishBlock;

@end

@implementation FFOpenRedPacketVC

+ (instancetype)showRedPackerWithData:(FFRewardConfig *)data
                          cancelBlock:(LIMCancelBlock)cancelBlock
                          finishBlock:(LIMFinishBlock)finishBlock {
    
    FFOpenRedPacketVC *redPacketView = [[self alloc] initRedPackerWithData:data
                                                                cancelBlock:cancelBlock
                                                                finishBlock:finishBlock];
    return redPacketView;
}

- (instancetype)initRedPackerWithData:(FFRewardConfig *)data
                          cancelBlock:(LIMCancelBlock)cancelBlock
                          finishBlock:(LIMFinishBlock)finishBlock {
    self = [super init];
    
    if (self) {
        
        _data = data;
        
        [self.alertWindow addSubview:self.view];
        [self.alertWindow addSubview:self.backgroundImageView];
        
        
        self.cancelBlock = cancelBlock;
        self.finishBlock = finishBlock;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeViewAction)];
        tapGesture.delegate = self;
        [self.view addGestureRecognizer:tapGesture];
        
    }
    return self;
}

- (UIWindow *)alertWindow {
    if (!_alertWindow) {
        _alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _alertWindow.windowLevel = UIWindowLevelAlert;
        _alertWindow.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
        [_alertWindow makeKeyAndVisible];
        _alertWindow.rootViewController = self;
    }
    return _alertWindow;
}

- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        
        UIImage *image =  [self imageNamed:@"bg_hongbao"];
        
        CGFloat width = ScreenWidth - 50 * ViewScaleIphone5Value;
        CGFloat height = width * (image.size.height / image.size.width);
        _backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(25 * ViewScaleIphone5Value, ScreenHeight / 2 - height / 2, width, height)];
        _backgroundImageView.image = image;
        _backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
        _backgroundImageView.userInteractionEnabled = YES;
        
        [_backgroundImageView addSubview:self.closeButton];
        
        UIView *containerView = [[UIView alloc] init];
        [_backgroundImageView addSubview:containerView];
        [containerView addSubview:self.userNameLabel];
        [containerView addSubview:self.avatarImageView];
        
        
        if (!_data.isExpired) {
            [_backgroundImageView addSubview:self.openButton];
            [_backgroundImageView addSubview:self.messageLabel];
            [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(_backgroundImageView.mas_centerX);
                make.top.equalTo(containerView.mas_bottom).offset(20);
            }];
        }else {
            [_backgroundImageView addSubview:self.tipsLabel];
            [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(containerView.mas_bottom).offset(20);
                make.left.equalTo(_backgroundImageView.mas_left);
                make.right.equalTo(_backgroundImageView.mas_right);
            }];
            [_backgroundImageView addSubview:self.checkDetailButton];
            [self.checkDetailButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(_backgroundImageView.mas_bottom).offset(-25);
                make.centerX.equalTo(_backgroundImageView.mas_centerX);
            }];
        }
        
        
        [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_backgroundImageView);
            make.top.equalTo(_backgroundImageView).offset(90);
            make.height.equalTo(@50);
        }];
        
        [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(containerView.mas_centerY);
            make.centerX.equalTo(containerView.mas_centerX).offset(15);
            
        }];
        
        [self.avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.userNameLabel.mas_left).mas_offset(-5);
            make.centerY.equalTo(containerView.mas_centerY);
            make.width.height.equalTo(@30);
        }];
        
        
        self.backgroundImageView.transform = CGAffineTransformMakeScale(0.05, 0.05);
        
        [UIView animateWithDuration:.15
                         animations:^{
            self.backgroundImageView.transform = CGAffineTransformMakeScale(1.05, 1.05);
        }completion:^(BOOL finish){
            [UIView animateWithDuration:.15
                             animations:^{
                self.backgroundImageView.transform = CGAffineTransformMakeScale(0.95, 0.95);
            }completion:^(BOOL finish){
                [UIView animateWithDuration:.15
                                 animations:^{
                    self.backgroundImageView.transform = CGAffineTransformMakeScale(1, 1);
                }];
            }];
        }];
    }
    return _backgroundImageView;
}

- (UIButton *)openButton {
    if (!_openButton) {
        
        CGFloat widthOrHeight = 100 * ViewScaleIphone5Value;
        
        _openButton = [[UIButton alloc]initWithFrame:CGRectMake(_backgroundImageView.frame.size.width/2 - widthOrHeight/2, _backgroundImageView.frame.size.height/2 + 60, widthOrHeight,widthOrHeight)];
        _openButton.adjustsImageWhenHighlighted = NO;
        [_openButton setImage:[self imageNamed:@"btn_kai"] forState:UIControlStateNormal];
        [_openButton addTarget:self action:@selector(openRedPacketAction) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _openButton;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        CGFloat widthOrHeight = 40 * ViewScaleIphone5Value;
        _closeButton = [[UIButton alloc]initWithFrame:CGRectMake(_backgroundImageView.frame.size.width/2 - widthOrHeight/2, _backgroundImageView.frame.size.height + 26, widthOrHeight, widthOrHeight)];
        [_closeButton setImage:[self imageNamed:@"btn_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeViewAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _closeButton;
}


- (UIButton *)checkDetailButton {
    if (!_checkDetailButton) {
        CGFloat widthOrHeight = 100 * ViewScaleIphone5Value;
        _checkDetailButton = [[UIButton alloc]initWithFrame:CGRectMake(_backgroundImageView.frame.size.width/2 - widthOrHeight/2, _backgroundImageView.frame.size.height + 26, widthOrHeight, widthOrHeight)];
        [_checkDetailButton setTitle:@"查看领取详情 >" forState:UIControlStateNormal];
        _checkDetailButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [_checkDetailButton setTitleColor:[UIColor colorWithRed:238/255.0 green:191/255.0 blue:130/255.0 alpha:1.0] forState:(UIControlStateNormal)];
        [_checkDetailButton addTarget:self action:@selector(checkDetailAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _checkDetailButton;
}


- (UIImageView *)avatarImageView {
    if (!_avatarImageView) {
        _avatarImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_backgroundImageView.frame.size.width/2 - 30, 30, 30, 30)];
        _avatarImageView.clipsToBounds = YES;
        _avatarImageView.layer.cornerRadius = 15;
        _avatarImageView.layer.borderWidth = 2;
        _avatarImageView.layer.borderColor = [UIColor colorWithRed:238/255.0 green:191/255.0 blue:130/255.0 alpha:1.0].CGColor;
//        [_avatarImageView setImage:_data.avatarImage];
        [_avatarImageView setImageWithURL:[NSURL URLWithString:_data.avatarImageUrl] placeholderImage:[WKApp shared].config.defaultAvatar];
        
    }
    return _avatarImageView;
}

- (UILabel *)userNameLabel {
    if (!_userNameLabel) {
        _userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 + 30, 35, _backgroundImageView.frame.size.width - 20, 20)];
        _userNameLabel.textColor = [UIColor colorWithRed:238/255.0 green:191/255.0 blue:130/255.0 alpha:1.0];
        _userNameLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        _userNameLabel.text = [NSString stringWithFormat:@"%@的红包", _data.userName];
        _userNameLabel.textAlignment = NSTextAlignmentCenter;
        _userNameLabel.preferredMaxLayoutWidth = _backgroundImageView.frame.size.width - 100;
        _userNameLabel.numberOfLines = 0;
    }
    return _userNameLabel;
}

- (UILabel *)tipsLabel {
    if (!_tipsLabel) {
        _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, _userNameLabel.frame.size.height + _userNameLabel.frame.origin.y + 10, _backgroundImageView.frame.size.width - 40, 200)];
        _tipsLabel.textColor = [UIColor colorWithRed:238/255.0 green:191/255.0 blue:130/255.0 alpha:1.0];
        _tipsLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
        _tipsLabel.text = [NSString stringWithFormat:@"%@", _data.content];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.numberOfLines = 0;
    }
    return _tipsLabel;
}

- (UILabel *)messageLabel {
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, _tipsLabel.frame.size.height + _tipsLabel.frame.origin.y + 10 * ViewScaleIphone5Value, _backgroundImageView.frame.size.width - 40, 27 * ViewScaleIphone5Value)];
        _messageLabel.textColor = [UIColor colorWithRed:238/255.0 green:191/255.0 blue:130/255.0 alpha:1.0];
        _messageLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:24];
        _messageLabel.text = _data.content;
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.preferredMaxLayoutWidth = _backgroundImageView.frame.size.width - 100;
        _messageLabel.numberOfLines = 3;
    }
    return _messageLabel;
}

- (void)closeViewAction {
    
    [UIView animateWithDuration:.2 animations:^{
        self.backgroundImageView.transform = CGAffineTransformMakeScale(0.2, 0.2);
        
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:.08
                         animations:^{
            self.backgroundImageView.transform = CGAffineTransformMakeScale(0.01, 0.01);
        }completion:^(BOOL finish){
            
            [self.alertWindow removeFromSuperview];
            self.alertWindow.rootViewController = nil;
            self.alertWindow = nil;
            
            if (self.cancelBlock) {
                self.cancelBlock();
            }
        }];
        
    }];
    
}

- (void)checkDetailAction {
    if (self.finishBlock) {
        [self.alertWindow removeFromSuperview];
        self.alertWindow.rootViewController = nil;
        self.alertWindow = nil;
        self.finishBlock(_data);
    }
}

- (void)openRedPacketAction {
    [_openButton.layer addAnimation:[self confirmViewRotateInfo] forKey:@"transform"];
}

- (CAKeyframeAnimation *)confirmViewRotateInfo {
    CAKeyframeAnimation *theAnimation = [CAKeyframeAnimation animation];
    
    theAnimation.values = [NSArray arrayWithObjects:
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0, 0.5, 0)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(3.13, 0, 0.5, 0)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(6.28, 0, 0.5, 0)],
                           nil];
    
    
    theAnimation.cumulative = YES;
    theAnimation.duration = .6;
    theAnimation.repeatCount = 3;
    theAnimation.removedOnCompletion = YES;
    theAnimation.fillMode = kCAFillModeForwards;
    theAnimation.delegate = self;
    
    return theAnimation;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
       shouldReceiveTouch:(UITouch *)touch {
    
    return (![_backgroundImageView pointInside:[touch locationInView:_backgroundImageView] withEvent:nil]);
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (self.finishBlock) {
        [self.alertWindow removeFromSuperview];
        self.alertWindow.rootViewController = nil;
        self.alertWindow = nil;
        self.finishBlock(_data);
    }
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

- (UIImage*)imageNamed:(NSString*)name {
    return [[WKApp shared] loadImage:name moduleID:@"LiMaoRedPackets"];
}

@end
